package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.event.FileEvent;
import com.cljz.makepassenger.event.UserInfoChangeEvent;
import com.cljz.makepassenger.present.activity.UserLogoP;
import com.cljz.makepassenger.utils.OtherUtils;
import com.cljz.makepassenger.utils.T;
import com.cljz.makepassenger.widget.multi_image_selector.MultiImageSelectorFragment;
import com.jakewharton.rxbinding.view.RxView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/12.
 */

public class UserLogoActivity extends BaseActivity<UserLogoP> implements MultiImageSelectorFragment.Callback {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.fl_image)
    FrameLayout flImage;
    private int mode;
    private int[] picScale;

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mDefaultCount = bundle.getInt(EXTRA_SELECT_COUNT, 9);
        mode = bundle.getInt(EXTRA_SELECT_MODE, MODE_MULTI);
        boolean isShow = bundle.getBoolean(EXTRA_SHOW_CAMERA, true);
        if (mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultList = bundle.getStringArrayList(EXTRA_DEFAULT_SELECTED_LIST);
            bundle.putStringArrayList(EXTRA_DEFAULT_SELECTED_LIST,resultList);
        }
        if (mode == MODE_SINGLE) {
            picScale = bundle.getIntArray(CutViewActivity.CUT_SCALE);
        }
//        bundle.putStringArrayList(MultiImageSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, resultList);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fl_image, Fragment.instantiate(this, MultiImageSelectorFragment.class.getName(), bundle))
                .commit();

        if (resultList == null || resultList.size() <= 0) {
            btnCommit.setText("完成");
            btnCommit.setEnabled(false);
        } else {
            updateDoneText();
            btnCommit.setEnabled(true);
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_logo;
    }

    @Override
    public UserLogoP newP() {
        return new UserLogoP();
    }


    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(ivBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        setResult(RESULT_CANCELED);
                        finish();
                    }
                });
        RxView.clicks(btnCommit)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (resultList != null && resultList.size() > 0) {
                            // 返回已选择的图片数据
                            Intent intent = getIntent();
                            Bundle bundle = new Bundle();
                            bundle.putStringArrayList("pic", resultList);
                            intent.putExtras(bundle);
                            setResult(RESULT_OK, intent);
                            Router.pop(UserLogoActivity.this);
//                    Bitmap bitmap = BitmapFactory.decodeFile(resultList.get(0));
//                    getP().getUploadImg(BitmapUtils.convertPicToString(bitmap));
                        }
                    }
                });

    }

    /**
     * 最大图片选择次数，int类型，默认9
     */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /**
     * 图片选择模式，默认多选
     */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /**
     * 是否显示相机，默认显示
     */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    /**
     * 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合
     */
    public static final String EXTRA_RESULT = "select_result";
    /**
     * 默认选择集
     */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_result";

    /**
     * 单选
     */
    public static final int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;

    private ArrayList<String> resultList = new ArrayList<>();
    private int mDefaultCount;

    /**
     * 拍照时存储拍照结果的临时文件
     */
    private File mTmpFile;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (mode == MODE_SINGLE) {
                Router.newIntent((Activity) App.getInstance())
                        .putString("path", mTmpFile.getAbsolutePath())
                        .putIntArray(CutViewActivity.CUT_SCALE, picScale)
                        .to(CutViewActivity.class)
                        .launch();
            }
//            Bitmap bitmap = BitmapFactory.decodeFile(mTmpFile.getAbsolutePath());
//            getP().getUploadImg(BitmapUtils.convertPicToString(bitmap));
        }
    }


    private void updateDoneText() {
        btnCommit.setText(String.format("%s(%d/%d)",
                "完成", resultList.size(), mDefaultCount));
    }

    @Override
    public void onSingleImageSelected(String path) {
//         startPhotoZoom(Uri.fromFile(new File(path)));
        Router.newIntent((Activity) App.getInstance())
                .putString("path", path)
                .putIntArray(CutViewActivity.CUT_SCALE, picScale)
                .to(CutViewActivity.class)
                .launch();
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        mTmpFile = OtherUtils.createFile(getApplicationContext());
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("output", Uri.fromFile(mTmpFile));
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("circleCrop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 5);
        intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 750);
        intent.putExtra("outputY", 450);
        intent.putExtra("return_1-data", true);
        startActivityForResult(intent, 3);
    }

    @Override
    public void onImageSelected(String path) {
        if (!resultList.contains(path)) {
            resultList.add(path);
        }
        // 有图片之后，改变按钮状态
        if (resultList.size() > 0) {
            updateDoneText();
            if (!btnCommit.isEnabled()) {
                btnCommit.setEnabled(true);
            }
        }

    }

    @Override
    public void onImageUnselected(String path) {
        if (resultList.contains(path)) {
            resultList.remove(path);
        }
        updateDoneText();
        // 当为选择图片时候的状态
        if (resultList.size() == 0) {
            btnCommit.setText("完成");
            btnCommit.setEnabled(false);
        }
    }

    @Override
    public void onCameraShot(File imageFile) {
        if (imageFile != null) {

            // notify system
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));

            Intent data = new Intent();
            resultList.add(imageFile.getAbsolutePath());
            data.putStringArrayListExtra(EXTRA_RESULT, resultList);
            setResult(RESULT_OK, data);
            finish();
        }
    }

    public void getUpLoadImgFail(String error) {

    }

    public void userLogoUpdate(String msg) {
        BusProvider.getBus().post(new UserInfoChangeEvent());
        T.getInstance().showShort(msg);
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    public void bindEvent() {
        BusProvider.getBus().toObservable(FileEvent.class)
                .compose(this.<FileEvent>bindToLifecycle())
                .subscribe(new Action1<FileEvent>() {
                    @Override
                    public void call(FileEvent fileEvent) {
                        mTmpFile = fileEvent.getCameraFile();
                    }
                });
    }
}
